﻿<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no" />
<link rel="shortcut icon" href="Images/ico/favicon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link type="text/css" rel="stylesheet" href="/layui/css/layui.css"  media="all">
<link rel="stylesheet" type="text/css" href="/css/mobiscroll.custom.min.css" />
<script src="/js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/js/mobiscroll.custom.min.js"></script>
<script type="text/javascript" src="/layui/layui.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/layui-post.js"></script>
<style type="text/css">
.cartpay .addr:before {top:16px;}
.layui-layer-title{padding:0!important;}
.lists div.l{width: 25%}
.lists div.r{width: 73%}
.white-color{background: #fff;border-radius: 10px;}
.layui-tab-title li {width: 50%;padding: 0;background: #dedada;}
.layui-tab-title .layui-this {background: #FFF;}
</style>
</head>
<body style="background: #F0F0F0;padding: 10px;">
<div class="ng-scope">
    <header class="ng-scope" style="">
        <h4 class="title-order">
            <a class="title-top" href="javascript:window.history.back();" onclick="insertBachCart()"></a>
            <a class="title-center">购物车</a>
            <a class="title-right" href="/index" onclick="insertBachCart()"></a>
        </h4>
    </header>
    <!--购物车空提示-->
    <div class="cartempty ng-scope ng-hide white-color" style="margin-top: 50px;padding-bottom: 100px;">
        <h3>亲，购物车空空的呢~</h3>
        <a href="/shop">去逛逛</a>
    </div>
    <!--/购物车空提示-->
    <div class="cartpay ng-scope" style="margin-top: 50px;">
        <div class="take-delivery white-color" style="border-radius: 20px 20px 10px 10px;">
            <div class="layui-tab" lay-filter="sendTypes">
                <ul class="layui-tab-title" style="border-radius: 20px 20px 0 0;">
                    <li class="layui-this" lay-id="1" style="border-radius: 20px 0 0 0;">外面配送</li>
                    <li lay-id="2" style="border-radius: 0 20px 0 0;">到店自取</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <div id="sendMethod">
                            <div id="defaultAddress"></div>
                            <div class="send-type">
                                <span style="width:20%;float:left;margin-left:30px;color:#666;font-size:14px">配送方式：</span>
                                <select style="width:70%;float:left;" class="input remark ng-pristine ng-untouched ng-valid ng-empty" id="sendType"></select>
                            </div>
                        </div>
                        <div id="writeAddress" class="ng-hide" style="background:#fff;height: 70px;">
                            <div style="height: 5px;"></div>
                            <a style="border-radius: 10px;" class="btn btn-default add_addr" onclick="addressAdd()">添加收货地址</a>
                        </div>
                    </div>
                    <div class="layui-tab-item">
                        <div style="color: #6b6868; font-weight: bold;font-size: 17px;padding: 10px;">河南信阳市罗山县宝城街道办事处行政中路233号 美味鸡蛋仔</div>
                        <div style="height: 80px;padding: 10px;line-height: 40px;">
                            <div style="width: 30%;height: 80px;float:left;">
                                <div class="section">
                                    <label>自取时间</label>
                                    <input type="text" class="layui-input" id="sendTime" style="width: 65px;display: inline;border: none;" />
                                    <i class="layui-icon layui-icon-right"></i>
                                </div>
                            </div>
                            <div style="width: 2.5%;height: 70px;margin-top:10px;float:left;margin-right: 3%; border-right: 0.1px solid #ebe4e4;"></div>
                            <div style="width: 64%;height: 80px;float:left;">
                                <div>预留电话</div>
                                <div><input id="telPhone" type="number" class="layui-input" placeholder="请输入预留电话" style="width: 60%;border:none;display: inline;"><i class="layui-icon layui-icon-edit"></i></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <section class="prolist_section" style="margin-top: 10px;">
            <ul id="prolist" class="lists white-color" style="padding: 10px;"></ul>
        </section>
        <!--底部结算导航-->
        <div class="cart ng-scope">
            <div class="r" onclick="insertOrder()"><a href="javascript:;">提交订单</a></div>
            <div class="l ng-binding c">
                ￥<label id="totalmoney">0</label>
                <span class="font11 points">本次消费获得积分：<span id="points" style="color: #fff;">0</span></span>
            </div>
        </div>
        <!--/底部结算导航-->
    </div>
</div>
<input type="hidden" id="addressId">
</body>
<script>
$.ajaxSetup({contentType: "application/json; charset=utf-8"});
var goodsIds=[],reqdataList=[],totalcartnumber = 0,totalmoney = 0,totalpoints = 0,loading;
var userInfo = $.parseJSON(sessionStorage.getItem("userInfo")),sendType = 1;// 配送类型1外卖配送2到店自取
var deliveryTypes = []
var theme = "ios",mode = "scroller",display = "bottom",lang="zh";
layui.use(['layer','form','element','util'], function(){
    loading = layer.load();
    $.post(geturl()+'/enums/select?token='+sessionStorage.getItem("token"), JSON.stringify({parentEnumCode:"DELIVERY_TYPE",orderByAscType:"enumCode"}), function (res) {
        for(var key in res.data.DELIVERY_TYPE) $('#sendType').append('<option value="'+key + '">' + res.data.DELIVERY_TYPE[key] + '</option>');
        $('#sendType').val("DELIVERY_TYPE_03").attr("disabled",true)
    })
    layui.element.on('tab(sendTypes)', function(){
        sendType = this.getAttribute('lay-id');
    });
    var nowDate = minDate().split(",")
    $("#sendTime").val((nowDate[3].length==1?"0"+nowDate[3]:nowDate[3])+":"+(nowDate[4].length==1?"0"+nowDate[4]:nowDate[4]))
    $('#sendTime').mobiscroll().time({
        theme: theme,
        mode: mode,
        display: display,
        lang: lang,
        minDate:new Date(parseInt(nowDate[0]),parseInt(nowDate[1]),parseInt(nowDate[2]),parseInt(nowDate[3]),parseInt(nowDate[4])),
        maxDate:new Date(parseInt(nowDate[0]),parseInt(nowDate[1]),parseInt(nowDate[2]),22,0)
    });
    $.post("/cateringCart/select",JSON.stringify({userId:userInfo.userId}),function(res){
        reqdataList = [];goodsIds = [];
        $("#prolist").html("")
        if(res.data.length === 0) {
            $(".cartempty").removeClass("ng-hide")
            $(".cartpay").addClass("ng-hide")
        }else{
            for(var i in res.data){
                let yxgg = !isEmpty(res.data[i].spacesName) ? '<p class="t" style="font-size: 10px;margin-top: 6px;">'+res.data[i].spacesName+'</p>': ""
                deliveryTypes.push(res.data[i].deliveryType)
                $("#prolist").append(
                    '<li price="'+res.data[i].goodsPrice+'" spacesId="'+res.data[i].spacesId+'" class="on" goodsId="'+res.data[i].goodsId+'" internum="'+res.data[i].interNum+'" cart="1">' +
                    '<div class="l">' +
                    '<a href="/detail?sysId='+res.data[i].goodsId+'"><img style="border-radius:10px;" src="'+res.data[i].goodsImg+'" class="img-responsive" alt="..." /></a>' +
                    '</div>' +
                    '<div class="r">' +
                    '<p class="t">'+res.data[i].goodsName+'</p>' +
                    '<div class="jifen">送积分：'+res.data[i].interNum+'</div>' +
                    yxgg +
                    '<p class="price">￥'+res.data[i].goodsPrice+'</p>' +
                    '<div class="showaddcart">' +
                    '<div class="num_con">' +
                    '<img src="img/num_l.png" class="img-responsive num_l" alt="..." />' +
                    '<span class="number" style="padding: 5px;">'+res.data[i].goodsNum+'</span>' +
                    '<img src="img/num_r.png" class="img-responsive num_r" alt="..." />' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</li>'
                )
                totalcartnumber += res.data[i].goodsNum
                totalmoney += res.data[i].goodsNum*res.data[i].goodsPrice
                totalpoints += res.data[i].goodsNum*res.data[i].interNum
                $("#"+res.data[i].goodsId).text(res.data[i].goodsNum)
                //将数据放入购物车
                if(goodsIds.indexOf(res.data[i].goodsId) === -1) {
                    let resdata = {};
                    goodsIds.push(res.data[i].goodsId)
                    resdata.goodsId = res.data[i].goodsId;
                    resdata.goodsNum = res.data[i].goodsNum
                    resdata.goodsPrice = res.data[i].goodsPrice
                    resdata.userId = userInfo.userId
                    resdata.spacesId = res.data[i].spacesId
                    reqdataList.push(resdata);
                }
            }
            $("#totalcartnumber").text(totalcartnumber);
            $("#totalmoney").text(totalmoney.toFixed(2));
            $("#points").text(totalpoints);
        }
    }).done(function(){
        if(deliveryTypes.indexOf("DELIVERY_TYPE_04") > -1){
            layui.element.tabChange('sendTypes', 2);
            layer.msg("商品包含上门自取，自动切换为到店自取",{icon:0,time:3000})
        }
    })
    //获取地址信息
    getAddress({userId:userInfo.userId,isDefault:1,isDel:0})

    //shop：加入购物车
    $(".lists li").each(function (i, model) {
        var objLi = $(this);
        //点击减数量
        $(objLi).find(".num_l").click(function () {
            var goodsId =$(objLi).attr("goodsId");
            var number = parseInt($(objLi).find(".number").text()) - 1;
            var cart = $(objLi).attr("cart");
            if (number > 0) {
                $(objLi).find(".number").text(number);
                if(goodsIds.indexOf(goodsId) > -1){
                    for(var i in reqdataList){
                        if(reqdataList[i].goodsId === goodsId) reqdataList[i].goodsNum = number;
                    }
                }
            } else {
                if(goodsIds.indexOf(goodsId) > -1) {
                    goodsIds.splice($.inArray(goodsId,goodsIds),1)
                    reqdataList.splice($.inArray(goodsId,reqdataList),1)
                }
                if (cart == 1) {//说明是购物车中的操作
                    $(objLi).remove();
                } else if (cart == 2) {//说明是外卖的操作
                    if (number == 0) {
                        $(objLi).find(".number").text(number);
                    }
                } else {
                    $(objLi).removeClass("on");
                }
            }
            if (number == 0 && reqdataList.length == 0) {
                $(".cartempty").removeClass("ng-hide")
                $(".cartpay").addClass("ng-hide")
                let data={userId:userInfo.userId}
                $.post("/cateringCart/delete",JSON.stringify(data))
            }
            CountNumPrice();
        });
        //点击加数量
        $(objLi).find(".num_r").click(function () {
            var goodsId =$(objLi).attr("goodsId");
            var reqdata={};
            var number = parseInt($(objLi).find(".number").text()) + 1;
            if(goodsIds.indexOf(goodsId) === -1) {
                goodsIds.push(goodsId)
                reqdata.goodsId = goodsId;
                reqdata.goodsNum = number
                reqdata.goodsPrice = $(".lists .on").attr("price")
                reqdata.spacesId = $(".lists .on").attr("spacesId")
                reqdata.userId = userInfo.userId
                reqdataList.push(reqdata);
            }else {
                for(var i in reqdataList){
                    if(reqdataList[i].goodsId === goodsId) reqdataList[i].goodsNum = number;
                }
            }
            $(objLi).find(".number").text(number);
            CountNumPrice();
        });
        //点击查看产品详情
        $(objLi).find(".view").click(function () {
            $(objLi).find(".detail").show(200);
        });
    });
})
function CountNumPrice() {
    var totalcartnumber = 0;//数量
    var totalmoney = 0;//价格
    var totalpoints = 0;//积分
    $(".lists .on").each(function (i, model) {
        var objLi = $(this);
        var number = parseInt($(objLi).find(".number").text());
        var price = parseFloat($(objLi).attr("price"));
        var inter = parseFloat($(objLi).attr("interNum"));
        totalcartnumber = totalcartnumber + number;
        totalmoney = totalmoney + (number * price);
        totalpoints = totalpoints + (number * inter);
    });
    $("#totalcartnumber").text(totalcartnumber);
    $("#totalmoney").text(totalmoney.toFixed(2));
    $("#points").text(totalpoints);
}
function insertOrder(){
    // 判断是否包含上门自取商品，如果有，则订单类型为上门自取
    if(sendType == 1 && deliveryTypes.indexOf("DELIVERY_TYPE_04") == -1){
        doInsertOrder()
    }else if(sendType == 1 && deliveryTypes.indexOf("DELIVERY_TYPE_04") > -1){
        layer.confirm('商品包含上门自取，确认切换为到店自取吗？',function(index){
            layui.element.tabChange('sendTypes', 2);
            layer.closeAll()
        });
    }else {
        doInsertOrder()
    }
}
function doInsertOrder(){
    let data={userId:userInfo.userId,orderCartList:reqdataList,sendIntegra:$("#points").html(),sendType: sendType,orderStatus:"ORDER_STATUS_01"}
    if(sendType == "1"){
        data.addressId = $("#addressId").val()
        data.remark = $("#remark").val()
    }else {
        data.remark = $("#telPhone").val()
        data.sendTime = $("#sendTime").val()
    }
    if(sendType == "1" && $("#addressId").val() === "") {
        layer.msg("请选择或添加收货地址", {icon: 0, time: 1500})
    }else if(sendType == "2" && $("#telPhone").val() === ""){
        layer.msg("请输入预留电话",{icon:0,time:1500})
    }else{
        $.post("/cateringOrder/insert",JSON.stringify(data),function(res){
            if(res.success) layer.msg(res.msg,{icon:1,time:1500},function(){
                window.location.href="/pay?orderId="+res.data;
            });
        })
    }
}
function insertBachCart(){
    $.post("/cateringCart/insertBach",JSON.stringify({userId:userInfo.userId,cartslist:reqdataList}))
}
function chooseAddress(){
    layer.open({
        type:2,
        area: ['100%', '50%'],
        title:["选择收货地址", 'text-align:center;font-size: 16px; font-weight: bold;'],
        closeBtn:1,
        btnAlign: 'c',
        offset: 'b',
        anim: 2,
        skin:'layui-layer-nobg',
        shadeClose:true,
        content:"/addresscho?addressId="+$("#addressId").val(),
        scrollbar:false,
    })
}
function getAddressId(id){
    $("#addressId").val(id)
    //更新地址信息
    getAddress({sysId:id,isDel:0})
}

function getAddress(data){
    $.post("/cateringAddress/select",JSON.stringify(data),function(res){
        $("#defaultAddress").html("")
        layer.close(loading)
        if(res.data.length === 0) {
            $("#writeAddress").removeClass("ng-hide")
            $("#sendMethod").addClass("ng-hide")
        }
        for(var i in res.data){
            $("#addressId").val(res.data[i].sysId)
            $("#telPhone").val(res.data[i].telPhone)
            $("#defaultAddress").append(
                '<div class="addr" onclick="chooseAddress()" style="padding: 10px 20px 0px 30px;">' +
                '<p style="color:#FA2C2A;line-height: 30px;height: 30px; font-size: 16px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" class="ng-binding">'+res.data[i].person+'  '+'  '+res.data[i].detail+'  '+res.data[i].telPhone+'</p>' +
                '<p class="edit"><a onclick="chooseAddress()">&nbsp;</a></p>' +
                '</div>' +
                '<div class="yujibox">' +
                '<div style="width:25%;float:left;margin-left:30px;color:#666;font-size:14px">送达时间：</div>' +
                '<div style="width:60%;float:left;color:#888;font-size:12px">预计30分钟</div>' +
                '</div>' +
                '<div class="remarkbox">' +
                '<span style="width:20%;float:left;margin-left:30px;color:#666;font-size:14px">备注：</span>' +
                '<input id="remark" class="input remark ng-pristine ng-untouched ng-valid ng-empty" placeholder="点此输入备注" type="text">' +
                '</div>'
            )
        }
    })
}
function addressAdd(){
    parent.layer.open({
        type:2,
        area: ['100%', '100%'],
        title:["新增收货地址", 'text-align:center;font-size: 16px; font-weight: bold;padding-left: 50px;'],
        closeBtn:1,
        btnAlign: 'c',
        offset: 'b',
        anim: 0,
        skin:'layui-layer-nobg',
        shadeClose:true,
        content:"/addressadd",
        scrollbar:false,
    })
}
//最小日期（当前日期）当前时间半小时后
function minDate(){
    var now = new Date();
    now.setMinutes(now.getMinutes() + 31);
    return now.getFullYear()+","+(now.getMonth()+1)+","+(now.getDay())+","+(now.getHours()) + ',' + (now.getMinutes())
}
//最大日期（当前日期）当天时间22:00:00
function maxDate(){
    return '22:00:00'
}
</script>
</html>
